package x.trident.core.db.mp.fieldfill;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectionException;
import x.trident.core.enums.YesOrNotEnum;

import java.util.Date;

import static x.trident.core.db.api.constants.DbFieldConstants.*;


/**
 * 字段自动填充工具，在mybatis-plus执行更新和新增操作时候，会对指定字段进行自动填充，例如 create_time 等字段
 *
 * @author 林选伟
 * @date 2020/10/16 17:14
 */
@Slf4j
public class CustomMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            // 设置 CREATED_AT(BaseEntity)
            setValue(metaObject, CREATED_AT, new Date());

            // 设置删除标记 默认N-删除
            setValue(metaObject, DEL_FLAG, YesOrNotEnum.N.getCode());

        } catch (ReflectionException e) {
            log.warn("CustomMetaObjectHandler处理过程中无相关字段，不做处理");
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            // 设置 UPDATED_AT(BaseEntity)
            setValue(metaObject, UPDATED_AT, new Date());
        } catch (ReflectionException e) {
            log.warn("CustomMetaObjectHandler处理过程中无相关字段，不做处理");
        }
    }

    /**
     * 设置属性
     */
    private void setValue(MetaObject metaObject, String fieldName, Object value) {
        Object originalAttr = getFieldValByName(fieldName, metaObject);
        if (ObjectUtil.isEmpty(originalAttr)) {
            setFieldValByName(fieldName, value, metaObject);
        }
    }

}
